package com.fone.player.play.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseFragment;
import com.fone.player.client.Reporter;
import com.fone.player.client.VgdetailRst;
import com.fone.player.client.VgdetailRst.Cnt;
import com.fone.player.client.VgdetailRst.Ext;
import com.fone.player.entity.ContentSubscribe;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.adapter.VideoLiveCardAdapter;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;

/**
 * 节目单
 * 
 * @author kongxiaojun
 * @since 2014-4-30
 */
@SuppressLint("ValidFragment")
public class VideoLiveCardFragment extends BaseFragment {

	private static final String TAG = "VideoLiveCardFragment";
	/** 内容 */
	private View contentView;
	/** 列表 */
	private ListView cList;

	private String[] dayOfWeeks;

	private VideoLiveCardAdapter liveCardAdapter;
	private Handler mHandler;

	public VideoLiveCardFragment() {
		super();
		mHandler = new Handler(Looper.getMainLooper());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		contentView = inflater.inflate(R.layout.video_livecard, null);
		cList = (ListView) contentView.findViewById(R.id.video_livecard_list);
		this.dayOfWeeks = getResources().getStringArray(R.array.day_of_week);
		VgdetailRst videoDetail = ((FonePlayerActivity) getActivity()).getVgdetailRst();
		List<ContentSubscribe> subscribes = null;
		if (videoDetail != null && videoDetail.exts != null && videoDetail.exts.extList != null) {
			for (Ext ext : videoDetail.exts.extList) {
				if (ext.name.equals("节目单")) {
					subscribes = setSubscribes(ext.cntList, videoDetail.vgurl);
				}
			}
		}
		liveCardAdapter = new VideoLiveCardAdapter(subscribes);
		cList.setAdapter(liveCardAdapter);
		cList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Reporter.logEvent(Reporter.EventId.CLICK_DETAIL_BOOK_BTN);
				ContentSubscribe sub = (ContentSubscribe) liveCardAdapter.getItem(arg2);
				if (sub.getContentSubscribeTime() != 0) {
					if (sub.getContentSubscribeTime() > System.currentTimeMillis()) {
						// 检查是否已经预约
						ContentSubscribe sub2 = StorageModule.getInstance().getContentSubscribeByNameAndTime(sub.getContentSubscribeName(), sub.getContentSubscribeTime());
						if (sub2 != null) {
							L.v(TAG, "节目单已经预约了。。。取消预约");
							// 已经预约了
							// 删除数据库中的对应项
							int id = sub2.getContentSubscribeId();
							// 取消预约
							StorageModule.getInstance().deleteContentSubscribeById(id);
							Toast.makeText(getActivity(), R.string.cancel_reservation_toast, Toast.LENGTH_SHORT).show();
						} else {
							L.v(TAG, "节目单添加预约到数据库。。。");
							// 添加预约到数据库
							long id = StorageModule.getInstance().addContentSubscribe(sub);
							if (id == -1) {
								L.v(TAG, "节目单预约失败！！id ==-1");
								return;
							}
							L.v(TAG, "节目单预约成功！！id ==" + id);
							Toast.makeText(getActivity(), R.string.has_reservation_toast, Toast.LENGTH_SHORT).show();
						}
						liveCardAdapter.notifyDataSetChanged();
					}
				}
			}

		});
		// 设置选中位置
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (cList != null && liveCardAdapter != null) {
					cList.setSelection(liveCardAdapter.getPlayingPostion());
				}
			}
		}, 1000);

		return contentView;
	}

	private List<ContentSubscribe> setSubscribes(List<Cnt> cnts, String vgurl) {

		if (cnts != null && cnts.size() > 0) {
			List<ContentSubscribe> subscribes = new ArrayList<ContentSubscribe>();
			for (int i = 0; i < cnts.size(); i++) {
				Cnt cnt = cnts.get(i);
				if (cnts.size() > i + 1) {
					Cnt cnt2 = cnts.get(i + 1);
					String date1 = cnt.time.substring(0, 10);
					String date2 = cnt2.time.substring(0, 10);
					// 先加cnt1一项，再加一个组
					ContentSubscribe sub = new ContentSubscribe();
					sub.setContentSubscribeName(cnt.name);
					sub.setContentSubscribeTime(FoneUtil.parserDate(cnt.time, "yyyy-MM-dd HH:mm").getTime());
					sub.setContentSubscribeUrl(vgurl);
					subscribes.add(sub);
					if (!date1.equals(date2)) {// 加一个组
						ContentSubscribe sub2 = new ContentSubscribe();
						Calendar cal = Calendar.getInstance();
						cal.setTime(FoneUtil.parserDate(cnt2.time, "yyyy-MM-dd HH:mm"));
						int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
						String groupName = String.format(getString(R.string.live_card_group), dayOfWeeks[dayofweek - 1]);

						sub2.setContentSubscribeTime(0);
						sub2.setContentSubscribeName(groupName);
						sub2.setContentSubscribeUrl(vgurl);
						subscribes.add(sub2);
					}
				}
			}
			return subscribes;
		}
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		contentView = null;
		if (cList != null) {
			cList.removeAllViewsInLayout();
			cList = null;
		}
		dayOfWeeks = null;
		liveCardAdapter = null;
	}

}
